﻿namespace Ngs.Data
{
    using System;

    /// <summary>
    /// Aggregate of mappings for 2-way mapping between Poco and Linq Provider.
    /// It also serves as the object factory, although a factory method is provided.
    /// </summary>
    /// <typeparam name="TEntity"></typeparam>
    /// <typeparam name="TObject"></typeparam>
    public class ObjectMap<TObject, TEntity> where TObject : new()
    {

        #region Constructors

        public ObjectMap()
            : this(string.Empty)
        {
        }

        public ObjectMap(string entityName)
        {
            this.EntityName = !string.IsNullOrEmpty(entityName) ? entityName : typeof(TEntity).Name;
        }

        public ObjectMap(string entityName, Action<TEntity, TObject> toObject, Action<TObject, TEntity> toEntity)
            : this(entityName)
        {
            this.EntityToObject = toObject;
            this.ObjectToEntity = toEntity;
        }
        #endregion

        public string EntityName { get; set; }

        public Action<TEntity, TObject> EntityToObject { get; set; }

        public Action<TObject, TEntity> ObjectToEntity { get; set; }

        public TObject ConverToObject(TEntity entity)
        {
            ExceptionFactory.ThrowInvalidOperation(EntityToObject == null);
            TObject obj = new TObject();
            this.EntityToObject(entity, obj);
            return obj;
        }

    }
}
